const {executeQuery} = require('../config/db_config')
const express = require('express')

let cartRouter = express.Router()
cartRouter.use(express.json())

/**
 * 查询购物车列表
 */
cartRouter.get("/",async (req,resp)=>{
  const id = req.query.id
   const sql = `select * from cart where user_id=${id}`
  const res = await executeQuery(sql)
  resp.send({
    code:200,
    msg:'success',
    data:res
  })
})
/**
 * 添加商品到购物车
 */
cartRouter.post("/",async (req,resp)=>{
  
  const r = await executeQuery(`select * from cart where goods_id=${req.body.data.id} and user_id=${req.body.data.user_id}`)
  let sql
  if(r.length!=0){
      sql = `update  cart set num = ${req.body.data.num+r[0].num} where goods_id=${req.body.data.id} and user_id=${req.body.data.user_id} `
  }else{
      sql = `insert into cart(goods_id,user_id,num) values(${req.body.data.id},${req.body.data.user_id},${req.body.data.num}) `
  }
  const res = await executeQuery(sql)
  resp.send({
    code:200,
    msg:'success',
    data:res
  })
})
/**
 * 从购物车中移除商品
 */
cartRouter.delete("/",async (req,resp)=>{
  let sql 
  if(req.query.c_num-req.query.num==0){
    sql = `delete  from cart where goods_id=${req.query.id} and user_id=${req.query.user_id}`
  }else{
    sql = `update cart set num=${req.query.c_num-req.query.num} where goods_id=${req.query.id} and user_id=${req.query.user_id}`
  }
  const res = await executeQuery(sql)
  resp.send({
    code:200,
    msg:'success',
    data:res
  })
})

module.exports={
  cartRouter
}